/**
 * 微信JSSDK工具类
 * 用于在手机微信访问或开发环境下首次访问时引入微信JSSDK
 */

import { logger } from './logger';

// 全局标记，避免重复引入
let jssdkLoaded = false;

/**
 * 检测是否为微信环境
 */
export function isWeChat(): boolean {
  const ua = navigator.userAgent.toLowerCase();
  return ua.includes('micromessenger');
}

/**
 * 检测是否为开发环境
 */
export function isDevelopment(): boolean {
  return import.meta.env.MODE === 'development';
}

/**
 * 动态引入微信JSSDK
 */
export function loadWeChatJSSDK(): Promise<void> {
  return new Promise((resolve, reject) => {
    // 如果已经加载过，直接返回
    if (jssdkLoaded) {
      resolve();
      return;
    }

    // 检查是否在微信环境或开发环境
    if (!isWeChat() && !isDevelopment()) {
      resolve();
      return;
    }

    // 创建script标签引入JSSDK
    const script = document.createElement('script');
    script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js';
    script.onload = () => {
      jssdkLoaded = true;
      logger.log('微信JSSDK加载成功');
      resolve();
    };
    script.onerror = (error) => {
      logger.error('微信JSSDK加载失败:', error);
      reject(error);
    };

    document.head.appendChild(script);
  });
}

/**
 * 初始化微信分享配置
 */
export async function initWeChatShare(config: {
  title: string;
  desc: string;
  link: string;
  imgUrl?: string;
}): Promise<void> {
  try {
    // 确保JSSDK已加载
    await loadWeChatJSSDK();

    // 等待JSSDK完全加载
    if (typeof window.wx === 'undefined') {
      await new Promise(resolve => setTimeout(resolve, 100));
    }

    if (typeof window.wx === 'undefined') {
      logger.warn('微信JSSDK未加载成功');
      return;
    }

    // 获取分享配置
    const { sharePageInfo } = await import('@/api/system');
    const shareConfig = await sharePageInfo({
      title: config.title,
      url: config.link,
    });

    if (shareConfig.code === 200) {
      const { appId, timestamp, nonceStr, signature } = shareConfig.data;

      // 配置微信JSSDK
      window.wx.config({
        debug: shareConfig.data.debug,
        appId,
        timestamp,
        nonceStr,
        signature,
        jsApiList: shareConfig.data.jsApiList,
        openTagList: shareConfig.data.openTagList,
      });

      // 配置分享
      window.wx.ready(() => {
        // 分享给朋友
        if (window.wx && window.wx.updateAppMessageShareData) {
          window.wx.updateAppMessageShareData({
            title: config.title,
            desc: config.desc,
            link: config.link,
            imgUrl: config.imgUrl || 'https://www.xqnmz.com/static/image/default.jpg',
          });
        }

        // 分享到朋友圈
        if (window.wx && window.wx.updateTimelineShareData) {
          window.wx.updateTimelineShareData({
            title: config.title,
            link: config.link,
            imgUrl: config.imgUrl || 'https://www.xqnmz.com/static/image/default.jpg',
          });
        }

        logger.log('微信分享配置成功');
      });

      window.wx.error((error: any) => {
        logger.error('微信JSSDK配置失败:', error);
      });
    }
  }
  catch (error) {
    logger.error('初始化微信分享失败:', error);
  }
}

// 扩展window对象类型
declare global {
  interface Window {
    wx?: {
      config: (config: any) => void;
      ready: (callback: () => void) => void;
      error: (callback: (error: any) => void) => void;
      updateAppMessageShareData: (config: any) => void;
      updateTimelineShareData: (config: any) => void;
    };
  }
}

export default {
  isWeChat,
  isDevelopment,
  loadWeChatJSSDK,
  initWeChatShare,
};
